package com.example.airkiss.utils.wxpay;

import com.example.airkiss.utils.WXConstants;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.security.KeyStore;
import java.util.SortedMap;
import java.util.TreeMap;

public class WyTest {

    /**
     * @Author: HONGLINCHEN
     * @Description:微信退款
     * @Date: 2017-9-11 14:35
     * @return:
     */
    public static String wxPayRefund() {
        StringBuffer xml = new StringBuffer();
        String data = null;
            SortedMap<String,String> parameters = new TreeMap<String,String>();
            parameters.put("appid", WXConstants.WX_APPID);
            parameters.put("mch_id", WXConstants.MCH_ID);
            parameters.put("nonce_str", WXPayUtil.generateNonceStr());
            parameters.put("out_trade_no", "477493659881836544");
            parameters.put("out_refund_no", WXPayUtil.generateNonceStr());
            parameters.put("fee_type", "CNY");
            parameters.put("total_fee", "1");
            parameters.put("refund_fee", "1");
            parameters.put("op_user_id", WXConstants.MCH_ID);
        try {
            parameters.put("sign", WXPayUtil.generateSignedXml(parameters, WXConstants.KEY));
            data =WXPayUtil.mapToXml(parameters);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public static void main(String[] args) throws Exception {

        String data = wxPayRefund();
        String s = wxPayBack(data);
        System.err.println(s);
    }

    /**
     * 证书使用
     * 微信退款
     */
    public static String wxPayBack( String data) throws Exception {
        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File("D:\\zhengshu\\apiclient_cert.p12"));
        String result="";
        try {
            keyStore.load(instream, WXConstants.MCH_ID.toCharArray());
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, WXConstants.MCH_ID.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {
            HttpPost httppost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");
            StringEntity entitys = new StringEntity(data);
            httppost.setEntity((HttpEntity) entitys);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    String text="";
                    String t="";
                    while ((text=bufferedReader.readLine()) != null) {
                        t+=text;
                    }
                    byte[] temp=t.getBytes("gbk");//这里写原编码方式
                    String newStr=new String(temp,"utf-8");//这里写转换后的编码方式
                    result=newStr;
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        return result;
    }
}
